<template>
  <el-container>
    <el-header>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.prevent>
        <el-form-item label="租户名">
          <el-input
            v-model="searchForm.tenantName"
            placeholder="租户名"
            @keyup.enter="onSearch"
          ></el-input>
        </el-form-item>        
        <el-form-item label="应用名">
          <el-input
            v-model="searchForm.appName"
            placeholder="应用名"
            @keyup.enter="onSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="状态">
            <el-option
              v-for="item in licenseStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="default" @click="onReset">重置</el-button>
          <el-button type="default" @click="onAddLicense" icon="CirclePlus"
            >新增许可</el-button
          >
        </el-form-item>
      </el-form>
    </el-header>
    <el-divider direction="horizontal"></el-divider>
    <el-main class="cus-main">
      <el-table :data="licenseList" style="width: 100%">
        <el-table-column
          prop="id"
          label="ID"
          v-if="false"
        ></el-table-column>
        <el-table-column
          prop="tenantCode"
          label="租户编码"
          v-if="false"
        ></el-table-column>
        <el-table-column
          prop="tenantName"
          label="租户名"
        ></el-table-column>
        <el-table-column
          prop="appCode"
          label="应用编码"
          v-if="false"
        ></el-table-column>
        <el-table-column
          prop="appName"
          label="应用名"
        ></el-table-column>
        <el-table-column
          prop="appDesc"
          label="应用描述"
        ></el-table-column>
        <el-table-column
          prop="userLimit"
          label="用户数"
        ></el-table-column>
        <el-table-column
          prop="expiredAt"
          label="过期日期"
        >
        <template #default="scope">
              {{
                scope.row.expiredAt.replaceAll(" 00:00:00", "")
              }}
          </template>
      </el-table-column>
        <el-table-column prop="status" label="状态" >
          <template #default="scope">
            <el-tag :type="scope.row.status === 2 ? 'success' : 'danger'">
              {{
                licenseStatus.find((l) => l.value === scope.row.status).label
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="onFreeze(scope.row)"
              v-if="scope.row.status === 2"
              >冻结</el-button
            >
            <el-button
              link
              type="primary"
              @click="onUnFreeze(scope.row)"
              v-if="scope.row.status === 3"
              >解冻</el-button
            >
            <el-button
              link
              type="primary"
              @click="onApprove(scope.row)"
              v-if="scope.row.status === 1"
              >审批</el-button
            >
            <el-button
              link
              type="primary"
              @click="onDelete(scope.row)"
              v-if="scope.row.status !== 2"
              >删除</el-button
            >
            <el-button
              link
              type="primary"
              @click="onRenew(scope.row)"
              v-if="scope.row.status === 4"
              >续费</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal"
      >
      </el-pagination>
    </el-main>
    <el-dialog v-model="dialogVisible" title="新增许可" width="30%" header-class="dialog-custom-header">
      <el-divider direction="horizontal" style="width: 95%"></el-divider>
      <el-form :model="newLicenseForm" label-width="70px">
        <el-form-item label="应用编码">
          <el-input v-model="newLicenseForm.appCode"></el-input>
        </el-form-item>
        <el-form-item label="租户编码">
          <el-input v-model="newLicenseForm.tenantCode"></el-input>
        </el-form-item>
        <el-form-item label="用户数">
          <el-input v-model="newLicenseForm.userLimit" type="number"></el-input>
        </el-form-item>
        <el-form-item label="过期日期">
          <el-date-picker
            v-model="newLicenseForm.expiredAt"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { get, post, put, del } from "@/utils/request";

const licenseStatus = ref([]);
const dialogVisible = ref(false);
const searchForm = reactive({
  appName: null,
  tenantName: null,
  status: null,
});
const newLicenseForm = reactive({
  appCode: "",
  tenantCode: "",
  userLimit: 1,
  status: "1",
  expiredAt: null,
});
const licenseList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const listTotal = ref(0);

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};
const onReset = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = null;
  });
};
const onSearch = () => {
  let params = {
    appName: searchForm.appName,
    tenantName: searchForm.tenantName,
    status: searchForm.status,
    page: currentPage.value,
    size: pageSize.value,
  };
  get("/tmo/licenses", params)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        licenseList.value = res.data.data.data;
        listTotal.value = res.data.data.total;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onAddLicense = () => {
  Object.keys(newLicenseForm).forEach((key) => {
    newLicenseForm[key] = null;
  });
  newLicenseForm.status = licenseStatus.value[0].value;
  dialogVisible.value = true;
};

const onFreeze = (row) => {
  // 实现冻结逻辑
  let payload = {
    status: 3,
  };
  put("/tmo/licenses/" + row.id, payload)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        const index = licenseList.value.findIndex(
          (item) => item.id === row.id
        );
        if (index !== -1) {
          licenseList.value[index].status = 3;
        }
        ElMessage.success("冻结成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};
const onUnFreeze = (row) => {
  let payload = {
    status: 2,
  };
  put("/tmo/licenses/" + row.id, payload)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        const index = licenseList.value.findIndex(
          (item) => item.id === row.id
        );
        if (index !== -1) {
          licenseList.value[index].status = 2;
        }
        ElMessage.success("解冻成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onRenew = (row) => {
  // 实现续费逻辑
  console.log("续费:", row);
};

const onApprove = (row) => {
  // 实现审批逻辑
  let payload = {
    status: 2,
  };
  put("/tmo/licenses/" + row.id, payload)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        const index = licenseList.value.findIndex(
          (item) => item.id === row.id
        );
        if (index !== -1) {
          licenseList.value[index].status = 2;
        }
        ElMessage.success("审批成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onDelete = (row) => {
  del("/tmo/licenses/" + row.id)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        licenseList.value = licenseList.value.filter(
          (item) => item.id !== row.id
        );
        ElMessage.success("删除成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onSubmit = async () => {
  let succ = false;
  let payload = {
    appCode: newLicenseForm.appCode,
    tenantCode: newLicenseForm.tenantCode,
    userLimit: newLicenseForm.userLimit,
    expiredAt: newLicenseForm.expiredAt,
  };
  await post("/tmo/licenses", payload)
    .then((res) => {
      if (res.data.code === 0) {
        // licenseList.value.push({
        //   ...newLicenseForm,
        //   id: res.data.data.id,
        // });
        onSearch();
        succ = true;
        ElMessage.success("新增成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
    if (succ) {
      dialogVisible.value = false;
    }
};

onMounted(async() => {
  // 初始化字典
  await get("/tmo/licenses/status")
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        licenseStatus.value = res.data.data.data;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
  onSearch();
});
</script>

